package dao;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import bean.User;

/**
 * 
 * @author Pascal Kuendig
 * @version 10.07.2013
 *
 */
public class UserDAO extends AbstractDAO{
	
	private static UserDAO UserDAOSingelton;
	
	private UserDAO(){
		
	}
	
	public static UserDAO getInstance(){
		
		if(null == UserDAOSingelton){
			UserDAOSingelton = new UserDAO();
		}
		
		return UserDAOSingelton;
	}
	
	/**
	 * 
	 * @param Username, Passwort
	 * @return null = Login falsch
	 * @return UserObject = Login korrekt
	 * @throws SQLException 
	 * @throws IOException 
	 */
	public User checkLogin(String username, String passwort) throws SQLException, IOException{
		
		User logedUser = null;
		
		//Login check
		boolean loginResult = true;
		String sql = super.getDaoPropertie("getUserByNameAndPasswort");
		sql = sql.replace("????", username);
		sql = sql.replace("****", passwort);
		ResultSet rs = super.executeSelectQueryWithResultSet(sql);		
		
		if (!rs.next()){
				//User doesnt exist
				loginResult = false;
			}else{
				logedUser = new User(rs.getInt("userPK"),rs.getString("nachname"), rs.getString("vorname"), rs.getString("benutzername"), rs.getString("passwort"), rs.getBoolean("isAdmin"), rs.getDouble("kontostand"));
			}
		
		//Statement & ResultSet schliessen
		rs.getStatement().close();
		rs.close();
		
		if(!loginResult){
			return null;
		}else{
			return logedUser;
		}
	}
	
	/**
	 * 
	 * @param newUser
	 * @return true -> User eingef�gt
	 * @return false -> User nicht eingef�gt
	 * @throws SQLException
	 * @throws IOException 
	 */
	public synchronized boolean insertNewUser(User newUser) throws SQLException, IOException{
		//Pruefen ob User bereits existiert
		if (!checkIfUsernameExists(newUser.getBenutzername())){
			boolean insertResult = false;
			
			String sql = super.getDaoPropertie("insertNewUser");
			sql = sql.replace("????", newUser.getNachname());
			sql = sql.replace("****", newUser.getVorname());
			sql = sql.replace("----", newUser.getBenutzername());
			sql = sql.replace("++++", newUser.getPasswort());
			sql = sql.replace("!!!!", String.valueOf(newUser.getIsAdmin()));
			sql = sql.replace("....", String.valueOf(newUser.getKontostand()));
			
			int returnExecuteQuery = super.executeInsertQuery(sql);
			if (returnExecuteQuery != 0){
				insertResult = true;
			}
			return insertResult;
		}else{
			return false;
		}
	}
	
	private boolean checkIfUsernameExists(String username) throws SQLException, IOException{
		boolean userExists = false;
		String sql = super.getDaoPropertie("checkIfUsernameExists");
		sql = sql.replace("????", username);
		ResultSet rs = super.executeSelectQueryWithResultSet(sql);
		if(rs.next()){
			userExists = true;
		}
		rs.getStatement().close();
		rs.close();
		return userExists;
	}
}
